﻿using System;
using System.Data;
using System.Data.SqlClient;
using System.Text;
using System.Xml.Linq;
using System.Linq;
using System.Collections.Generic;
using Interprise.Framework.Customer.DatasetGateway;
using InterpriseSuiteEcommerceCommon.DTO;
using InterpriseSuiteEcommerceCommon.Extensions;
using InterpriseSuiteEcommerceCommon.Tool;
using InterpriseSuiteEcommerceCommon.InterpriseIntegration;

namespace InterpriseSuiteEcommerceCommon.InterpriseIntegration
{
    public class MobileCheckOutShippingPageLiteralRenderer : IShoppingCartHTMLLiteralRenderer
    {
        public void Render(InterpriseShoppingCart cart, ref StringBuilder output)
        {
            bool showPicsInCart = AppLogic.AppConfigBool("ShowPicsInCart");
            bool showLinkBack = AppLogic.AppConfigBool("LinkToProductPageInCart");
            bool hideUnitMeasure = AppLogic.AppConfigBool("HideUnitMeasure");
            bool showShipDateInCart = AppLogic.AppConfigBool("ShowShipDateInCart");
            bool showStockHints = AppLogic.AppConfigBool("ShowStockHints");
            bool vatEnabled = AppLogic.AppConfigBool("VAT.Enabled");

            var root = new XElement(DomainConstants.XML_ROOT_NAME);
            root.Add(new XElement("SKINID", cart.SkinID));
            root.Add(new XElement("CLICK_HERE_SUB_TEXT", AppLogic.GetString("checkoutcard.aspx.1", cart.SkinID, cart.ThisCustomer.LocaleSetting)));
            root.Add(new XElement("CLICK_HERE_TEXT", AppLogic.GetString("checkoutcard.aspx.2", cart.SkinID, cart.ThisCustomer.LocaleSetting)));

            string couponCode = string.Empty;
            bool hasCoupon = cart.HasCoupon(ref couponCode);
            if (hasCoupon)
            {
                root.Add(new XElement("HASCOUPON", hasCoupon));
                root.Add(new XElement("COUPON_HEADER_TEXT", AppLogic.GetString("checkoutshipping.aspx.14", cart.SkinID, cart.ThisCustomer.LocaleSetting)));
                root.Add(new XElement("COUPON_TEXT", AppLogic.GetString("checkoutshipping.aspx.15", cart.SkinID, cart.ThisCustomer.LocaleSetting)));
                root.Add(new XElement("COUPON_VALUE", couponCode.ToHtmlEncode()));
            }

            root.Add(new XElement("CHECKOUTSHIPPING_HEADER_TEXT", AppLogic.GetString("mobile.checkoutshipping.aspx.13", cart.SkinID, cart.ThisCustomer.LocaleSetting)));
            foreach (CartItem item in cart.CartItems)
            {
                var lineItemRow = item.AssociatedLineItemRow;

                var xmlcartItem = new XElement("CART_ITEMS");
                root.Add(xmlcartItem);

                string producthref = InterpriseSuiteEcommerceCommon.InterpriseHelper.MakeItemLink((string)lineItemRow["ItemCode"]);
                string productName = !string.IsNullOrEmpty(lineItemRow["ItemDescription"].ToString()) ? lineItemRow["ItemDescription"].ToString().ToHtmlEncode() : lineItemRow["ItemName"].ToString().ToHtmlEncode();

                xmlcartItem.Add(new XElement("SHOWPICSINCART", showPicsInCart));
                xmlcartItem.Add(new XElement("SHOWSHIPDATEINCART", showShipDateInCart));
                xmlcartItem.Add(new XElement("SHOW_LINKBACK", showLinkBack));
                xmlcartItem.Add(new XElement("CART_ITEMCODE", lineItemRow["ItemCode"].ToString()));
                xmlcartItem.Add(new XElement("CART_ITEM_ID", lineItemRow["counter"].ToString()));
                xmlcartItem.Add(new XElement("PRODUCTLINKNAME", productName));

                if (showPicsInCart)
                {
                    var img = ProductImage.Locate("product", item.ItemCounter, "icon");
                    if (null != img)
                    {
                        string seTitle = string.Empty;
                        string seAltText = string.Empty;
                        string itemCode = itemCode = InterpriseHelper.GetInventoryItemCode(item.ItemCounter);
                        AppLogic.GetSEImageAttributes(itemCode, "ICON", AppLogic.GetLanguageCode(cart.ThisCustomer.LocaleSetting), ref seTitle, ref seAltText);

                        xmlcartItem.Add(new XElement("PRODUCTIMAGEPATH", img.src));
                        xmlcartItem.Add(new XElement("PRODUCTIMAGETITLE", seTitle));
                        xmlcartItem.Add(new XElement("PRODUCTIMAGEALT", seAltText));
                    }
                }

                switch ((string)lineItemRow["ItemType"])
                {
                    case Interprise.Framework.Base.Shared.Const.ITEM_TYPE_MATRIX_GROUP:

                    #region "ITEM_TYPE_MATRIX_ITEM"
                    case Interprise.Framework.Base.Shared.Const.ITEM_TYPE_MATRIX_ITEM:

                        xmlcartItem.Add(new XElement("ITEM_TYPE", "ITEM_TYPE_MATRIX_ITEM"));
                        if (showLinkBack)
                        {
                            using (var con = DB.NewSqlConnection())
                            {
                                con.Open();
                                using (var reader = DB.GetRSFormat(con, "SELECT ItemCode FROM InventoryMatrixItem with (NOLOCK) WHERE MatrixItemCode = {0}", DB.SQuote(lineItemRow.ItemCode)))
                                {
                                    if (reader.Read())
                                    {
                                        xmlcartItem.Add(new XElement("PRODUCT_HREF", InterpriseSuiteEcommerceCommon.InterpriseHelper.MakeItemLink(DB.RSField(reader, "ItemCode"))));
                                    }
                                }
                            }
                        }

                        var matrixAttributes = AppLogic.GetMatrixItemAttributes(lineItemRow.ItemCode, Customer.Current.LanguageCode);
                        var matrixDetails = new StringBuilder();

                        matrixAttributes.ForEach(itemAttributes =>
                        {
                            matrixDetails.AppendFormat("&nbsp;&nbsp;{0}:{1}<br />", Security.HtmlEncode(itemAttributes.AttributeValue), Security.HtmlEncode(itemAttributes.AttributeValueDescription));
                        });

                        xmlcartItem.Add(new XElement("MATRIXDETAILS", matrixDetails.ToString()));

                        break;
                    #endregion

                    #region "ITEM_TYPE_KIT"
                    case Interprise.Framework.Base.Shared.Const.ITEM_TYPE_KIT:

                        xmlcartItem.Add(new XElement("ITEM_TYPE", "ITEM_TYPE_KIT"));
                        xmlcartItem.Add(new XElement("KIT_EDIT_IMAGE_ALT", cart.SkinID, AppLogic.GetString("shoppingcart.cs.4", 1, cart.ThisCustomer.LocaleSetting)));

                        string href = InterpriseSuiteEcommerceCommon.InterpriseHelper.MakeItemLink(item.ItemCode) + "?kcid={0}".FormatWith(item.Id.ToString());
                        xmlcartItem.Add(new XElement("KIT_EDIT_HREF", href));

                        xmlcartItem.Add(new XElement("PRODUCT_HREF", producthref));
                        xmlcartItem.Add(new XElement("KIT_SHOWDETAILSTEXT", AppLogic.GetString("mobile.wishlist.aspx.2", cart.SkinID, cart.ThisCustomer.LocaleSetting)));
                        xmlcartItem.Add(new XElement("KIT_HIDEDETAILSTEXT", AppLogic.GetString("mobile.wishlist.aspx.3", cart.SkinID, cart.ThisCustomer.LocaleSetting)));

                        var kitDetailRelation = cart.SalesOrderDataset.GetRelation(
                                                        cart.SalesOrderDataset.CustomerSalesOrderDetailView,
                                                        cart.SalesOrderDataset.CustomerItemKitDetailView
                        );

                        var kitItems = new XElement("KIT_ITEMS");
                        var lineItemRows = lineItemRow.GetChildRows(kitDetailRelation);

                        lineItemRows.ForEach(kitItemDetail =>
                        {
                            var kitDetail = ((SalesOrderDatasetGateway.CustomerItemKitDetailViewRow)kitItemDetail);
                            var kitItem = new XElement("KITITEM");
                            kitItem.Add(new XElement("QTY", Localization.ParseLocaleDecimal(kitDetail.QuantityPerKit, cart.ThisCustomer.LocaleSetting)));
                            kitItem.Add(new XElement("DESCRIPTION", Security.HtmlEncode(kitDetail.ItemDescription)));
                            kitItems.Add(kitItem);
                        });
                       
                        xmlcartItem.Add(kitItems);
                        break;

                    #endregion

                    #region  "STOCK"
                    default:
                        xmlcartItem.Add(new XElement("ITEM_TYPE", "ITEM_TYPE_STOCK"));
                        //xml already processed above.
                        xmlcartItem.Add(new XElement("PRODUCT_HREF", producthref));
                        break;
                    #endregion
                }

                xmlcartItem.Add(new XElement("SHOWSTOCKHINTS", showStockHints));
                if (showStockHints)
                {
                    if (showShipDateInCart)
                    {
                        string allocatedQty = Localization.ParseLocaleDecimal(item.m_AllocatedQty, cart.ThisCustomer.LocaleSetting);
                        xmlcartItem.Add(new XElement("ALLOCATEDQTY", allocatedQty));
                        if (item.m_AllocatedQty > 0)
                        {
                            xmlcartItem.Add(new XElement("SHIPPING_TEXT", AppLogic.GetString("mobile.shoppingcart.cs.2", cart.SkinID, cart.ThisCustomer.LocaleSetting)));
                        }

                        var reserveCol = cart.GetReservation(item.ItemCode);
                        if (reserveCol.Count > 0) xmlcartItem.Add(new XElement("SHIPPINGON_TEXT", AppLogic.GetString("mobile.shoppingcart.cs.3", cart.SkinID, cart.ThisCustomer.LocaleSetting)));

                        xmlcartItem.Add(new XElement("RESERVATION_COUNT", reserveCol.Count));
                        var reservationItems = reserveCol
                                                .Select(r => new XElement("RESERVATIONITEM",
                                                        new XElement("RESERVE_ITEMCODE", r.ItemCode),
                                                        new XElement("RESERVE_SHIPDATE", r.ShipDate.ToShortDateString()),
                                                        new XElement("RESERVE_QTY", Localization.ParseLocaleDecimal(r.QtyReserved, cart.ThisCustomer.LocaleSetting))));
                        xmlcartItem.Add(reservationItems);
                    }
                }

                #region "Unit Measure"

                xmlcartItem.Add(new XElement("NOT_HIDE_UNIT_MEASURE", !hideUnitMeasure));
                if (!hideUnitMeasure)
                {
                    xmlcartItem.Add(new XElement("UNITMEASUREDESCRIPTION", AppLogic.GetUnitMeassureDescription(item.UnitMeasureCode).ToHtmlEncode()));
                }

                #endregion

                xmlcartItem.Add(new XElement("INPUTQUANTITYVALUE", Localization.ParseLocaleDecimal(item.m_Quantity, cart.ThisCustomer.LocaleSetting)));
                xmlcartItem.Add(new XElement("HASCOUPON", hasCoupon));
                if (hasCoupon)
                {
                    // Sales Price 
                    xmlcartItem.Add(new XElement("COUPON_SALESPRICERATE", cart.ThisCustomer.FormatBasedOnMyCurrency(lineItemRow.SalesPriceRate)));
                    xmlcartItem.Add(new XElement("COUPON_DISCOUNTRATE", cart.ThisCustomer.FormatBasedOnMyCurrency(lineItemRow.CouponDiscountRate)));
                }

                xmlcartItem.Add(new XElement("VATENABLED", vatEnabled.ToStringLower()));

                // Extended Price
                decimal extPriceRate = item.Price;
                //(decimal)item.AssociatedLineItemRow.Table.Compute("SUM(ExtPriceRate)", string.Format("ItemCode = '{0}'", item.ItemCode));//

                if (vatEnabled)
                {
                    string vatSettingText = AppLogic.GetString("showproduct.aspx.37", cart.ThisCustomer.SkinID, cart.ThisCustomer.LocaleSetting);
                    if (cart.ThisCustomer.VATSettingReconciled == VatDefaultSetting.Inclusive)
                    {
                        extPriceRate += item.TaxRate;
                        vatSettingText = AppLogic.GetString("showproduct.aspx.38", cart.ThisCustomer.SkinID, cart.ThisCustomer.LocaleSetting);
                        xmlcartItem.Add(new XElement("VATAMOUNT_TEXT", AppLogic.GetString("showproduct.aspx.41", cart.ThisCustomer.SkinID, cart.ThisCustomer.LocaleSetting)));
                        xmlcartItem.Add(new XElement("VATAMOUNT_VALUE", cart.ThisCustomer.FormatBasedOnMyCurrency(item.TaxRate)));
                    }

                    xmlcartItem.Add(new XElement("PRICEFORMATTED", InterpriseHelper.FormatCurrencyForCustomer(extPriceRate, cart.ThisCustomer.CurrencyCode)));
                    xmlcartItem.Add(new XElement("VATSETTING_TEXT", vatSettingText));
                }
                else
                {
                    xmlcartItem.Add(new XElement("PRICEFORMATTED", InterpriseSuiteEcommerceCommon.InterpriseHelper.FormatCurrencyForCustomer(extPriceRate, cart.ThisCustomer.CurrencyCode)));
                }
            }

            decimal subTotal = cart.SalesOrderDataset.CustomerSalesOrderView[0].SubTotalRate;
            decimal tax = cart.SalesOrderDataset.CustomerSalesOrderView[0].TaxRate;
            decimal dueTotal = cart.SalesOrderDataset.CustomerSalesOrderView[0].TotalRate;
            decimal balance = cart.SalesOrderDataset.CustomerSalesOrderView[0].BalanceRate;
            string currencyCode = cart.ThisCustomer.CurrencyCode;

            if (vatEnabled)
            {
                if (cart.ThisCustomer.VATSettingReconciled == VatDefaultSetting.Inclusive)
                {
                    subTotal += tax;
                }
                else
                {
                    dueTotal -= tax;
                    balance -= tax;
                }
            }

            root.Add(new XElement("SUBTOTAL_TEXT", AppLogic.GetString("shoppingcart.cs.27", cart.SkinID, cart.ThisCustomer.LocaleSetting)));
            root.Add(new XElement("SUBTOTAL_VALUE", InterpriseHelper.FormatCurrencyForCustomer(subTotal, currencyCode)));

            root.Add(new XElement("DUETOTAL_CAPTION", AppLogic.GetString("shoppingcart.cs.1008", cart.SkinID, cart.ThisCustomer.LocaleSetting)));
            root.Add(new XElement("DUETOTAL_VALUE", InterpriseHelper.FormatCurrencyForCustomer(dueTotal, currencyCode)));

            root.Add(new XElement("TOTAL_CAPTION", AppLogic.GetString("shoppingcart.cs.11", cart.SkinID, cart.ThisCustomer.LocaleSetting)));
            root.Add(new XElement("TOTAL_VALUE", InterpriseHelper.FormatCurrencyForCustomer(balance, currencyCode)));

            string html = new XmlPackage2("page.checkoutshipping_template.xml.config", root).TransformString();
            output.Append(html);
        }
    }
}
